<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/movie.css">
    <link rel="stylesheet" href="http://at.alicdn.com/t/font_1309180_m0vigzfu7y.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <title>电影详情</title>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>
<body>
    <!-- 导航栏 -->
    <nav>
        <ul>
            <li><a href="dashboard.html"><i class="fas fa-home"></i> 返回</a></li>
            <li class="search-bar">
                <input type="text" id="searchInput" placeholder="搜索...">
                <button onclick="search()"><i class="iconfont iconchazhao"></i></button>
            </li>
            <li><a href="https://www.taobao.com" target="_blank">编者推荐</a></li>
            <li><a href="https://yiyan.baidu.com/" target="_blank">AI导航</a></li>
            <li><a href="javascript:goToMyPage()">我的</a></li>
        </ul>
    </nav>

    <div class="movie-header">
        <div class="movie-poster">
            <img id="moviePoster" src="" alt="Movie Poster" style="width: 100%; height: 100%;">
        </div>
        <div class="movie-details">
            <div class="movie-info">
                <div id="movieTitle" class="movie-title">电影名称</div>
                <div id="movieDirector" class="movie-meta">导演: 导演名</div>
                <div id="movieActors" class="movie-meta">演员: 演员1, 演员2, 演员3</div>
                <div id="movieRating" class="movie-meta">评分: 8.5</div>
                <div id="movieIntro" class="movie-meta">简介: 这是电影的简介。</div>
            </div>
            <div id="actionButtons" class="action-buttons">
                <button class="favorite-button" onclick="favoriteMovie()"><i class="fas fa-heart"></i>&nbsp;收藏</button>
                <button class="recommend-button" onclick="recommendMovie()"><i class="fas fa-thumbs-up"></i> &nbsp;推荐</button>
                <button class="subfavorite-button" onclick="subfavoriteMovie()"><i class="fas fa-heart"></i>&nbsp;取消收藏</button>
            </div>
        </div>
    </div>

    <div class="review-buttons">
        <button id="longReviewBtn" class="active" onclick="showReviews('long')">长评</button>
        <button id="shortReviewBtn" onclick="showReviews('short')">短评</button>
    </div>

    <div class="review-input">
        <select id="reviewRating" style="display: none;">
            <option value="">选择评分</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
            <option value="6">6</option>
            <option value="7">7</option>
            <option value="8">8</option>
            <option value="9">9</option>
            <option value="10">10</option>
        </select>
        <textarea id="reviewInput" placeholder="输入您的评论..."></textarea>
        <button id="submitReviewBtn" onclick="submitReview()">发送长评</button>
    </div>

    <div class="reviews" id="reviews">
        <!-- 评论列表 -->
    </div>

    <script>
        let currentReviewType = 'long';
        let currentUserType = localStorage.getItem('identity') || 1; // 假设用户类型存储在localStorage中，0为普通用户，1为非普通用户，2为管理员
        const filmId = localStorage.getItem('selectedFilmId');
        const userId = localStorage.getItem('user_id');
        const token = localStorage.getItem('access_token');
        let allComments = {}; // 保存所有评论
        function goToMyPage() {
            const identity = localStorage.getItem('identity');
            if (identity === '0') {
                window.location.href = 'user_dashboard.html';
            } else if (identity === '1') {
                window.location.href = 'superadmin_dashboard.html';
            } else if (identity === '2') {
                window.location.href = 'admin_dashboard.html';
            }
        }

        window.onload = function() {
            // 获取电影信息并展示（假设已从localStorage中获取）
            const moviesData = JSON.parse(localStorage.getItem('moviesData'));
            let movie;

            for (let category in moviesData) {
                movie = moviesData[category].find(m => m.film_id == filmId);
                if (movie) break;
            }

            if (movie) {
                document.getElementById('moviePoster').src = movie.www_http;
                document.getElementById('movieTitle').textContent = movie.film_name;
                document.getElementById('movieDirector').textContent = `导演: ${movie.director}`;
                document.getElementById('movieActors').textContent = `演员: ${movie.actor}`;
                document.getElementById('movieRating').textContent = `评分: ${movie.film_mark}`;
                document.getElementById('movieIntro').textContent = `简介: ${movie.introductory}`;
            } else {
                console.error("电影信息未找到");
            }
            // 新增的函数：检查用户的 ban_not 状态并禁用评论功能
async function checkBanStatus() {
    const userId = localStorage.getItem('user_id');
    const token = localStorage.getItem('access_token');
    const apiUrl = 'http://192.168.78.248:5000/user_infor';

    const requestData = {
        user_id: userId,
        code: 1 // 用户标记
    };

    try {
        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify(requestData)
        });

        if (response.ok) {
            const result = await response.json();
            if (result.infor.ban_not === 1) {
                disableCommenting();
                Swal.fire('您已被禁言，不能进行评论');
            }
        } else {
            console.error("Failed to fetch user info");
        }
    } catch (error) {
        console.error("Error fetching user info:", error);
    }
}
async function fetchUserInfo() {                //用户禁言
    const token = localStorage.getItem('access_token');
    const userId = localStorage.getItem('user_id');
    const apiUrl = 'http://192.168.78.248:5000/user_infor';

    const requestData = {
        user_id: userId,
        code: 1 // 用户标记
    };

    try {
        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify(requestData)
        });

        if (response.status === 200) {
            const result = await response.json();
            if (result.infor.ban_not === true) {
                disableCommenting();
            }
        } else {
            console.error("Failed to fetch user info");
        }
    } catch (error) {
        console.error("Error fetching user info:", error);
    }
}
fetchUserInfo()
// 禁用评论功能的函数
function disableCommenting() {
    document.getElementById('reviewInput').disabled = true;
    document.getElementById('reviewRating').disabled = true;
    document.getElementById('submitReviewBtn').disabled = true;
}

// 修改 window.onload 函数以调用 checkBanStatus
window.onload = function() {
    // 获取电影信息并展示（假设已从localStorage中获取）
    const moviesData = JSON.parse(localStorage.getItem('moviesData'));
    let movie;

    for (let category in moviesData) {
        movie = moviesData[category].find(m => m.film_id == filmId);
        if (movie) break;
    }

    if (movie) {
        document.getElementById('moviePoster').src = movie.www_http;
        document.getElementById('movieTitle').textContent = movie.film_name;
        document.getElementById('movieDirector').textContent = `导演: ${movie.director}`;
        document.getElementById('movieActors').textContent = `演员: ${movie.actor}`;
        document.getElementById('movieRating').textContent = `评分: ${movie.film_mark}`;
        document.getElementById('movieIntro').textContent = `简介: ${movie.introductory}`;
    } else {
        console.error("电影信息未找到");
    }

    // 调用获取评论的函数
    fetchComments();

    // 检查用户是否被禁言
    checkBanStatus();

    if (parseInt(currentUserType) !== 0) {
        document.getElementById('reviewInput').disabled = true;
        document.getElementById('reviewRating').disabled = true;
        document.getElementById('submitReviewBtn').disabled = true;
        document.getElementById('actionButtons').style.display = 'none'; // 隐藏收藏和推荐按钮
    }

    // 如果是管理员，获取被禁言或封禁的用户
    if (parseInt(currentUserType) === 2) {
        fetchBannedUsers();
    }
}


            // 调用获取评论的函数
            fetchComments();
            if (parseInt(currentUserType) !== 0) {
                document.getElementById('reviewInput').disabled = true;
                document.getElementById('reviewRating').disabled = true;
                document.getElementById('submitReviewBtn').disabled = true;
                document.getElementById('actionButtons').style.display = 'none'; // 隐藏收藏和推荐按钮
            }

            // 如果是管理员，获取被禁言或封禁的用户
            if (parseInt(currentUserType) === 2) {
                fetchBannedUsers();
            }
        }

        async function fetchComments() {
    try {
        const requestData = {
            user_id: parseInt(userId),
            film_id: parseInt(filmId),
            type: 'all'
        };

        const response = await fetch('http://192.168.78.248:5000/comment', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify(requestData)
        });

        if (response.ok) {
            const data = await response.json();
            allComments = data; // 保存所有评论
            sortCommentsByTopFlag(data);
            displayComments(data, currentReviewType);
        } else {
            console.error('获取评论失败');
        }
    } catch (error) {
        console.error('请求错误', error);
    }
}

async function fetchBannedUsers() {
    try {
        const requestData = {
            user_id: parseInt(userId),
            code: 2
        };

        const response = await fetch('http://192.168.78.248:5000/manage_user', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify(requestData)
        });

        if (response.ok) {
            const data = await response.json();
            displayBanButtons(data);
        } else {
            console.error('获取被禁言或封禁的用户失败');
        }
    } catch (error) {
        console.error('请求错误', error);
    }
}

function displayBanButtons(data) {
    const reviews = document.querySelectorAll('.review');

    reviews.forEach(review => {
        const userId = review.getAttribute('data-user-id');
        const user = data.find(u => u.user_id == userId);

        if (user) {
            const muteButton = document.createElement('button');
            muteButton.textContent = '禁言';
            muteButton.style.color = 'red';
            muteButton.disabled = user.ban_not === 1;
            muteButton.onclick = () => muteUser(user.user_id);

            const blockButton = document.createElement('button');
            blockButton.textContent = '封禁';
            blockButton.style.color = 'darkred';
            blockButton.disabled = user.block_not === 1;
            blockButton.onclick = () => banUser(user.user_id);

            review.appendChild(muteButton);
            review.appendChild(blockButton);
        }
    });
}

async function getUserStatus(targetUserId) {
    const requestData = {
        user_id: 21002, // 管理员id
        get_id: targetUserId
    };

    try {
        const response = await fetch('http://192.168.78.248:5000/infor_get', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify(requestData)
        });

        if (response.ok) {
            const data = await response.json();
            return data.infor;
        } else {
            console.error('获取用户状态失败');
            return null;
        }
    } catch (error) {
        console.error('请求错误', error);
        return null;
    }
}

async function muteUser(targetUserId) {
    const userInfo = await getUserStatus(targetUserId);

    if (userInfo && userInfo.ban_not) {
        Swal.fire('用户已被禁言');
        return;
    }

    const { value: banReason } = await Swal.fire({
        title: '输入禁言理由',
        input: 'text',
        inputLabel: '禁言理由',
        inputPlaceholder: '请输入禁言理由',
        showCancelButton: true,
        inputValidator: (value) => {
            if (!value) {
                return '你需要输入理由!';
            }
        }
    });

    if (banReason) {
        const requestData = {
            user_id: parseInt(userId),
            content: {
                ban_not: 1,
                ban_reason: banReason,
                ban_ma_id: parseInt(userId),
            },
            user_be_done: targetUserId
        };

        try {
            const response = await fetch('http://192.168.78.248:5000/manage_user', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(requestData)
            });

            if (response.ok) {
                Swal.fire('用户已被禁言');
                document.querySelector(`.review[data-user-id="${targetUserId}"] button[style*="red"]`).disabled = true;
            } else {
                Swal.fire('禁言失败');
            }
        } catch (error) {
            console.error('请求错误', error);
            Swal.fire('禁言失败');
        }
    }
}

async function banUser(targetUserId) {
    const userInfo = await getUserStatus(targetUserId);

    if (userInfo && userInfo.block_not) {
        Swal.fire('用户已被封禁');
        return;
    }

    const { value: blockReason } = await Swal.fire({
        title: '输入封禁理由',
        input: 'text',
        inputLabel: '封禁理由',
        inputPlaceholder: '请输入封禁理由',
        showCancelButton: true,
        inputValidator: (value) => {
            if (!value) {
                return '你需要输入理由!';
            }
        }
    });

    if (blockReason) {
        const requestData = {
            user_id: parseInt(userId),
            content: {
                ban_not: 0,
                ban_reason: '',
                ban_ma_id: 0,
                block_not: 1,
                block_reason: blockReason,
            },
            user_be_done: targetUserId
        };

        try {
            const response = await fetch('http://192.168.78.248:5000/manage_user', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(requestData)
            });

            if (response.ok) {
                Swal.fire('用户已被封禁');
                document.querySelector(`.review[data-user-id="${targetUserId}"] button[style*="darkred"]`).disabled = true;
            } else {
                Swal.fire('封禁失败');
            }
        } catch (error) {
            console.error('请求错误', error);
            Swal.fire('封禁失败');
        }
    }
}





        function sortCommentsByTopFlag(data) {
            if (data.markcomment) {
                data.markcomment.sort((a, b) => b.markcomment_value.top_not - a.markcomment_value.top_not);
            }
            if (data.commentonfilm) {
                data.commentonfilm.sort((a, b) => b.top_not - a.top_not);
            }
        }

        function displayComments(data, type) {
    const reviewsContainer = document.getElementById('reviews');
    reviewsContainer.innerHTML = '';

    if (type === 'short') {
        // 处理短评
        if (data.markcomment) {
            data.markcomment.forEach(comment => {
                const reviewElement = createReviewElement(comment.markcomment_value, 'short');
                reviewElement.setAttribute('data-user-id', comment.markcomment_value.user_id); // 为管理员按钮添加用户ID
                const reCommentsContainer = document.createElement('div');
                reCommentsContainer.classList.add('recomments');

                comment.recomment.forEach(recomment => {
                    const reCommentElement = createReCommentElement(recomment);
                    reCommentsContainer.appendChild(reCommentElement);
                });

                reviewElement.appendChild(reCommentsContainer);

                const replyButton = createReplyButton(comment.markcomment_value.mark_id);
                reviewElement.appendChild(replyButton);

                if (comment.has_more_recomment) {
                    const loadMoreReCommentButton = createLoadMoreReCommentButton(comment.markcomment_value.mark_id);
                    reviewElement.appendChild(loadMoreReCommentButton);
                } else {
                    const noMoreReComments = createNoMoreCommentsElement();
                    reviewElement.appendChild(noMoreReComments);
                }

                reviewsContainer.appendChild(reviewElement);
            });

            if (data.has_more_mark) {
                const loadMoreButton = createLoadMoreButton('mark_commend');
                reviewsContainer.appendChild(loadMoreButton);
            } else {
                const noMoreComments = createNoMoreCommentsElement();
                reviewsContainer.appendChild(noMoreComments);
            }
        }
    } else {
        // 处理长评
        if (data.commentonfilm) {
            data.commentonfilm.forEach(comment => {
                const reviewElement = createReviewElement(comment, 'long');
                reviewElement.setAttribute('data-user-id', comment.user_id); // 为管理员按钮添加用户ID
                reviewsContainer.appendChild(reviewElement);
            });

            if (data.has_more_comment) {
                const loadMoreButton = createLoadMoreButton('comment_on_film');
                reviewsContainer.appendChild(loadMoreButton);
            } else {
                const noMoreComments = createNoMoreCommentsElement();
                reviewsContainer.appendChild(noMoreComments);
            }
        }
    }

    if (parseInt(currentUserType) === 2) {
        displayBanButtons(data); // 确保管理员按钮显示在每条评论旁
    }
}

function createReviewElement(comment, type) {
    const reviewElement = document.createElement('div');
    reviewElement.className = 'review';

    if (type === 'short') {
        reviewElement.innerHTML = `
            <div class="review-content">${comment.short_comment}</div>
            <div class="review-rating">评分: ${comment.mark}</div>
            <div class="review-user">用户ID: ${comment.user_id}</div>
            <div class="review-assist">点赞: ${comment.short_assist}</div>
            <button class="like-button" onclick="likeComment(${comment.user_id}, ${comment.mark_id}, ${comment.comment_pass}, 1, ${comment.top_not}, 1)">点赞</button>
        `;
    } else {
        reviewElement.innerHTML = `
            <div class="review-content">${comment.long_comment}</div>
            <div class="review-date">日期: ${new Date(comment.comment_date).toLocaleString()}</div>
            <div class="review-user">用户ID: ${comment.user_id}</div>
            <div class="review-assist">点赞: ${comment.comment_assist}</div>
            <button class="like-button" onclick="likeComment(${comment.user_id}, ${comment.film_comment_id}, ${comment.comment_pass}, 1, ${comment.top_not}, 0)">点赞</button>
        `;
    }

    if (comment.top_not) {
        const topBadge = document.createElement('div');
        topBadge.textContent = '置顶';
        topBadge.style.color = 'red';
        reviewElement.appendChild(topBadge);
    }

    // 添加禁言和封禁按钮
    if (parseInt(currentUserType) === 2) {
        const muteButton = document.createElement('button');
        muteButton.textContent = '禁言';
        muteButton.style.color = 'red';
        muteButton.onclick = () => muteUser(comment.user_id, comment.ban_not);
        
        const blockButton = document.createElement('button');
        blockButton.textContent = '封禁';
        blockButton.style.color = 'darkred';
        blockButton.onclick = () => banUser(comment.user_id, comment.block_not);

        reviewElement.appendChild(muteButton);
        reviewElement.appendChild(blockButton);
    }

    return reviewElement;
}


        function createReCommentElement(recomment) {
            const reCommentElement = document.createElement('div');
            reCommentElement.className = 'recomment';

            reCommentElement.innerHTML = `
                <div class="recomment-content">${recomment.recomment}</div>
                <div class="recomment-user">用户ID: ${recomment.user_id}</div>
                <div class="recomment-assist">点赞: ${recomment.re_assist}</div>
                <button class="like-button" onclick="likeComment(${recomment.user_id}, ${recomment.recomment_id}, ${recomment.recomment_pass}, 1, ${recomment.re_top_not}, 2)">点赞</button>
            `;

            if (recomment.re_top_not) {
                const topBadge = document.createElement('div');
                topBadge.textContent = '置顶';
                topBadge.style.color = 'red';
                reCommentElement.appendChild(topBadge);
            }

            return reCommentElement;
        }

        async function likeComment(user_id, id, comment_pass, assist, top, code) {
            const data = {
                user_id: user_id,
                id: id,
                comment_pass: comment_pass,
                assist: 1,
                top: top,
                code: code
            };
            try {
                const response = await fetch('http://192.168.78.248:5000/comment_new', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(data)
                });

                if (response.ok) {
                    // 更新当前显示的评论
                    fetchComments();
                } else {
                    const errorData = await response.json();
                    alert(`点赞失败: ${errorData.message}`);
                }
            } catch (error) {
                console.error('请求错误', error);
                alert('点赞失败');
            }
        }

        function createReplyButton(mark_id) {
            const replyButton = document.createElement('button');
            replyButton.textContent = '回复';
            replyButton.onclick = () => showReplyInput(mark_id);
            return replyButton;
        }

        function createLoadMoreButton(type) {
            const loadMoreButton = document.createElement('button');
            loadMoreButton.textContent = '显示更多评论';
            loadMoreButton.onclick = () => loadMoreComments(type);
            return loadMoreButton;
        }

        function createLoadMoreReCommentButton(mark_id) {
            const loadMoreReCommentButton = document.createElement('button');
            loadMoreReCommentButton.textContent = '显示更多回评';
            loadMoreReCommentButton.onclick = () => loadMoreReComments(mark_id);
            return loadMoreReCommentButton;
        }

        function createNoMoreCommentsElement() {
            const noMoreComments = document.createElement('div');
            noMoreComments.textContent = '无更多评论';
            return noMoreComments;
        }

        async function loadMoreComments(type) {
            try {
                const requestData = {
                    user_id: parseInt(userId),
                    film_id: parseInt(filmId),
                    type,
                    last_assist: 0,
                    last_id: 0
                };

                const response = await fetch('http://192.168.78.248:5000/comment', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(requestData)
                });

                if (response.ok) {
                    const data = await response.json();
                    allComments = data; // 保存所有评论
                    displayComments(data, currentReviewType);
                } else {
                    console.error('加载更多评论失败');
                }
            } catch (error) {
                console.error('请求错误', error);
            }
        }

        async function loadMoreReComments(mark_id) {
            try {
                const requestData = {
                    user_id: parseInt(userId),
                    film_id: parseInt(filmId),
                    mark_id,
                    type: 'recomment',
                    last_assist: 0,
                    last_id: 0
                };

                const response = await fetch('http://192.168.78.248:5000/comment', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(requestData)
                });

                if (response.ok) {
                    const data = await response.json();
                    allComments = data; // 保存所有评论
                    displayComments(data, currentReviewType);
                } else {
                    console.error('加载更多回评失败');
                }
            } catch (error) {
                console.error('请求错误', error);
            }
        }

        function showReviews(type) {
            currentReviewType = type;
            document.getElementById('shortReviewBtn').classList.remove('active');
            document.getElementById('longReviewBtn').classList.remove('active');
            document.getElementById(type + 'ReviewBtn').classList.add('active');

            const reviewRating = document.getElementById('reviewRating');
            const submitReviewBtn = document.getElementById('submitReviewBtn');

            if (type === 'short') {
                reviewRating.style.display = 'inline';
                submitReviewBtn.textContent = '发送评论';
            } else {
                reviewRating.style.display = 'none';
                submitReviewBtn.textContent = '发送长评';
            }

            // 根据当前类型显示评论
            displayComments(allComments, type);
        }

        function formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        async function submitReview() {
            const reviewInput = document.getElementById('reviewInput').value.trim();
            const reviewRating = document.getElementById('reviewRating').value;
            let data = {
                user_id: parseInt(userId),
                code: currentReviewType === 'short' ? 1 : 0,
                content: {
                    film_id: parseInt(filmId),
                    user_id: parseInt(userId),
                }
            };

            if (reviewInput === '') {
                alert('填写评论');
                return;
            }

            if (currentReviewType === 'short') {
                if (reviewRating === '') {
                    alert('需要评分');
                    return;
                }

                if (reviewInput.length > 200) {
                    alert('评论字数最多200字，请重写');
                    return;
                }

                data.content.short_comment = reviewInput;
                data.content.mark = parseInt(reviewRating);
            } else {
                if (reviewInput.length > 2000) {
                    alert('评论字数最多2000字，请重写');
                    return;
                }

                data.content.long_comment = reviewInput;
                data.content.comment_date = formatDate(new Date());
            }

            try {
                const response = await fetch('http://192.168.78.248:5000/user_comment', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(data)
                });

                if (response.ok) {
                    alert('评论发送成功，等待审核通过');
                    document.getElementById('reviewInput').value = '';
                    if (currentReviewType === 'short') {
                        document.getElementById('reviewRating').value = '';
                    }
                    window.location.reload();  // 添加页面刷新
                } else {
                    const errorData = await response.json();
                    alert(`评论发送失败: ${errorData.message}`);
                }
            } catch (error) {
                console.error('请求错误', error);
                alert('评论发送失败');
            }
        }

        function displayNewComment(comment, rating) {
            const reviewsContainer = document.getElementById('reviews');
            const newReview = document.createElement('div');
            newReview.className = 'review';
            
            if (currentReviewType === 'short') {
                newReview.innerHTML = `
                    <div class="review-content">${comment}</div>
                    <div class="review-rating">评分: ${rating}</div>
                `;
            } else {
                newReview.innerHTML = `
                    <div class="review-content">${comment}</div>
                    <div class="review-date">日期: ${formatDate(new Date())}</div>
                `;
            }

            reviewsContainer.prepend(newReview);
        }

        function showReplyInput(mark_id) {
            const replyText = prompt('输入您的回复 (最多200字):');

            if (replyText === null) {
                // 用户取消输入
                return;
            }

            if (replyText.trim() === '') {
                alert('回复不能为空');
                return;
            }

            if (replyText.length > 200) {
                alert('字数过多，发送失败');
                return;
            }

            submitReply(mark_id, replyText);
        }

        async function submitReply(mark_id, reply) {
            const data = {
                user_id: parseInt(userId),
                code: 2, // 回复
                content: {
                    mark_id: mark_id,
                    user_id: parseInt(userId),
                    recomment: reply
                }
            };

            try {
                const response = await fetch('http://192.168.78.248:5000/user_comment', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(data)
                });

                if (response.ok) {
                    alert('回复发送成功');
                    // 更新当前显示的评论
                    fetchComments();
                } else {
                    const errorData = await response.json();
                    alert(`回复发送失败: ${errorData.message}`);
                }
            } catch (error) {
                console.error('请求错误', error);
                alert('回复发送失败');
            }
        }

        async function favoriteMovie() {
            const data = {
                user_id: parseInt(userId),
                code: 0,
                film_id: parseInt(filmId)
            };
            try {
                const response = await fetch('http://192.168.78.248:5000/user_love', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(data)
                });

                if (response.ok) {
                    alert('收藏成功');
                } else {
                    const errorData = await response.json();
                    alert(`收藏失败: ${errorData.message}`);
                }
            } catch (error) {
                console.error('请求错误', error);
                alert('收藏失败');
            }
        }

        async function subfavoriteMovie() {
            const data = {
                user_id: parseInt(userId),
                code: 1,
                film_id: parseInt(filmId)
            };
            try {
                const response = await fetch('http://192.168.78.248:5000/user_love', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(data)
                });

                if (response.ok) {
                    alert('取消收藏成功');
                } else {
                    const errorData = await response.json();
                    alert(`取消收藏失败: ${errorData.message}`);
                }
            } catch (error) {
                console.error('请求错误', error);
                alert('取消收藏失败');
            }
        }

        async function recommendMovie() {
            const data = {
                user_id: parseInt(userId),
                code: 3,
                film_id: parseInt(filmId)
            };
            try {
                const response = await fetch('http://192.168.78.248:5000/user_comment', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(data)
                });

                if (response.ok) {
                    alert('推荐成功');
                } else {
                    const errorData = await response.json();
                    alert(`推荐失败: ${errorData.message}`);
                }
            } catch (error) {
                console.error('请求错误', error);
                alert('推荐失败');
            }
        }

        function search() {
            const searchInput = document.getElementById('searchInput').value;
            const userId = localStorage.getItem('user_id') || 'guest';
            const token = localStorage.getItem('access_token');

            if (searchInput.trim() === '') {
                alert('请输入搜索内容');
                return;
            }

            const requestData = {
                user_id: parseInt(userId),
                search: searchInput
            };

            fetch('http://192.168.78.248:5000/search', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(requestData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'successfully') {
                    localStorage.setItem('searchResults', JSON.stringify(data.film));
                    window.location.href = 'search.html';
                } else {
                    alert('暂无搜索结果');
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }
    </script>
</body>
</html>
